import { ISoundManager } from "../../ADCore/Interfaces/IGameManager";
import { Dictionary } from "../../ADCore/Common/Dictionary";

export default class SoundManager implements ISoundManager {
    loadHandle: Laya.Handler
    loadSoud(listener: Function, caller?: any) {
        if (this.loadHandle) {
            this.loadHandle.recover();
        }
        this.loadHandle = Laya.Handler.create(caller, listener, null, false);
        var loadArray=[];
        for (let i = this.loadingNumber; i <SoundManager.musicList.count; i++) { 
            const sound = SoundManager.musicList.values[i];
            loadArray.push(sound.source); 
            this.loadingNumber++;
        }
        Laya.loader.load(loadArray,null,this.loadHandle,Laya.Loader.SOUND)
    }
    clear() {
        for (let i = 0; i < this.playList.count; i++) {
            const sound = this.playList.values.pop();
            sound.stop();
        }
        this.playList.clear();
    }
    destory() {
        this.clear();
        this.playList = null;
    }
    /**当前加载音乐数量 */
    loadingNumber: number = 0;

    static musicList: Dictionary<number, MusicData> = new Dictionary<number, MusicData>();
    playList: Dictionary<number, Laya.SoundChannel>;
    constructor() {
        this.playList = new Dictionary<number, Laya.SoundChannel>();
    }

    registerSound(soundEnum: number, source: string) {
        SoundManager.musicList.set(soundEnum, new MusicData(0, source));
    }
    registerMusic(soundEnum: number, source: string) {
        SoundManager.musicList.set(soundEnum, new MusicData(1, source));
    }
    play(soundEnum: number, loop: number = 0, compelet?): any {
        var sound = SoundManager.musicList.get(soundEnum);
        if (sound) {
            var soundChannel = sound.play(loop, compelet);
            loop == 0 && this.playList.set(soundEnum, soundChannel);
            return soundChannel;
        }
        else {
            console.debug("音效不存在!");
        }
        return null;
    }
    stop(soundEnum: number) {
        var sound = this.playList.get(soundEnum);
        sound && sound.stop();
    }

}
/**音效数据 */
export class MusicData {
    constructor(_types, _source) {
        this.types = _types;
        this.source = _source;
        if (this.types == 0) {
            this.play = (loop, compelet) => { return Laya.SoundManager.playSound(this.source, loop, compelet); };
        }
        else {
            this.play = (loop, compelet) => { return Laya.SoundManager.playMusic(this.source, loop, compelet); };
        }
    }
    //音效资源
    source: string;
    /**音效类型 0-音效，1=背景音乐 */
    types: number;
    /**
     * 播放函数
     * @param loop 循环次数
     * @param compelet 回调函数
     */
    play(loop, compelet): Laya.SoundChannel { return null; };
}